<template>
  <div>
    <div>分配角色界面</div>
    <el-checkbox-group v-model="checkListone">
      <el-checkbox v-for="(item, index) in rolePageList" :key="index" :label="item.roleName" />
    </el-checkbox-group>
  </div>
</template>
<script>
import RoleApi from "@/api/system-settings/role-manage";
import UserApi from "@/api/system-settings/user-manage"
export default {
  props: {
    userId: {
      type: Number | String,
      default: ''
    },
    userstu: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      rolePageList: [],
      checkListone: [],
      hasrolelist: [],
      hasidlist: []
    }
  },
  watch: {
    userstu: {
      handler (Val) {
        this.checkchange()
      }
    }
  },
  mounted () {
    this.getdatamet()
  },
  methods: {
    async getdatamet () {
      const res = await UserApi.getLoginUser()
      let params = {
        page: 1,
        size: 1000,
        superRoleFlg: res.superRoleFlg
      }
      RoleApi.queryPageByCondition(params).then(res => {
        this.rolePageList = res.data.content
        this.getrollehas()
      })
    },
    getrollehas () {
      RoleApi.queryListByUserId({ userId: this.userId }).then(res => {
        this.hasrolelist = res.data || []
        let that = this
        if (this.hasrolelist) {
          this.hasrolelist.forEach((item) => {
            this.rolePageList.forEach((itemtwo, indextwo) => {
              if (itemtwo.roleId === item.roleId) {
                that.hasidlist.push(item.roleId)
                that.checkListone.push(item.roleName)
              }
            })
          })
        }
      })
    },
    checkchange () {
      let that = this
      that.hasidlist = []
      if (this.checkListone.length > 0) {
        this.checkListone.forEach((item) => {
          this.rolePageList.forEach((itemtwo, indextwo) => {
            if (itemtwo.roleName === item) {
              that.hasidlist.push(itemtwo.roleId)
            }
          })
        })
      }
      let params = ``
      if (this.hasidlist.length > 0) {
        params = { roleIdList: this.hasidlist, userId: this.userId }
        UserApi.addRoleList(params).then(res => {
          if (res.success === true) {
            this.$emit('users', '')
            this.$message.success("分配角色成功")
          } else if (res.errCode === 200 && res.success === false) {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.info('分配的角色不能为空')
      }
    }
  }
}
</script>
